var auths = [],
	ws;
document.addEventListener('plusready', function() {
	ws = plus.webview.currentWebview();
	var spage = ws.spage;
	var ads = ws.ads;
	var id = plus.storage.getItem('id');
	var store_id = plus.storage.getItem('store_id');
	var lat = plus.storage.getItem('lat');
	var lng = plus.storage.getItem('lng');
//	console.log(store_id); 
	if(!store_id){
		dingwei();
	}
	if(id) {
		//		ws.close()
		relogin(ws.id);
		return;
	}
	
	$('.pass').on('click',function(){
		var user = $('.phone').val();
		console.log(user);
		if(!user){
			return;
		} 
//		console.log(1);
		$.ajax({
			type:"post",
			url:apiRoot + "?act=login&op=avatar",
			data:{
				user:user
			}, 
			dataType:'json',
			success:function(data){
				if(data.code == 200){
					$(".member_avatar").attr('src',user_pic + data.datas.member_avatar);
				}else{
					toast(data.datas.error);
				}
			}
		});
	})
	
	
	
	
	
	
	//	$.ajax({   
	//		type:"get",
	//		url:apiRoot + "/Home/Ziliao/disanf",
	//		dataType :'json',
	//		success:function(data){  
	//			if(data == 1){
	//				if(mui.os.android){
	//					$('.fenxiang').css('display','block');
	//				}else{
	//					$('.fenxiang').css('display','none');
	//				}
	//			}else{ 
	//				$('.fenxiang').css('display','block'); 
	//			}
	//		}
	//	});

	$('.res_pasw').on('click', function() {
		var user = $('.phone').val();
		var pass = $('.pass').val();
		if(!user || !pass) {
			plus.nativeUI.toast('账号或密码不能为空');
			return;
		}
		//		console.log(apiRoot+"/Home/Member/login/user/133/pass/123456");
		plus.nativeUI.showWaiting('登录中...');
		$.ajax({
			type: "post",
			url: apiRoot + "?act=login&op=index",
			data: {
				user: user,
				pass: pass
			},
			dataType: 'json',
			success: function(data) {
				plus.nativeUI.closeWaiting('');
				console.log(JSON.stringify(data));
				//				console.log(data['aid']); 
				if(data.msg == '登陆成功！') {
					toast(data.msg);
					plus.storage.setItem('user', data.username + '');
					plus.storage.setItem('name', data.truename + '');
					plus.storage.setItem('id', data.userid + '');
					plus.storage.setItem('userpic', data.member_avatar + '');
					relogin(ws.id);
				} else {
					toast(data.msg);
					//					var newnat = plus.nativeUI.showWaiting();
					//					var newweb = plus.webview.create('index.html','index.html');
					//					newweb.addEventListener('loaded',function(){
					//						newnat.close();
					//						newweb.show('slide-in-right',20);
					//					},false)
				}
			},
			error: function(e) {
				plus.nativeUI.closeWaiting();
				plus.nativeUI.toast("连接失败，请重试。");
				//			 	plus.nativeUI.toast('失去连接1');return;
			}
		});

	})

	//获取登录权限列表
	plus.oauth.getServices(function(data) {
		for(var i in data) {
			var service = data[i];
			auths[service.id] = service;
			//			console.log(JSON.stringify(data));

		}
	}, function(e) {
		plus.nativeUI.toast('获取第三方登录失败!');
	})
	//第三方登录
	$('.weixinlogin').on('click', function() {
		plus.nativeUI.showWaiting('登录中...');
		oauthLogin('weixin');
		dingwei();

	})

	$('.qqlogin').on('click', function() {
		plus.nativeUI.showWaiting('登录中...');
		oauthLogin('qq');
		dingwei();
	})

	$('.sinalogin').on('click', function() {
		plus.nativeUI.showWaiting('登录中...');
		oauthLogin('sinaweibo');
		dingwei();
	})

	/**
	 * 权限认证
	 * @param {Object} id
	 */
	function oauthLogin(id) {

		var s = auths[id];
		if(!s.authResult) {
			s.login(function(success) {
				//				alert(id+"oauthLogin");
				getAuthsInfo(id);
				return;
			}, function(e) {
				//				alert(JSON.stringify(e));
				plus.nativeUI.closeWaiting();
				toast('登录认证失败');
				return;
			})
		} else {
			//alert(id+"oauthLogin2");
			getAuthsInfo(id);
			//alert('weixin');     
			return;
		}
	}

	/**
	 * 获取用户信息
	 */
	function getAuthsInfo(id) {

		//		alert(auths);     
		var s = auths[id],
			userinfo = null,
			datas = null,
			user = null,
			figureurl_qq_2 = null,
			gender = null,
			access_token = null,
			openid = null,
			oauthtype = s.id,
			nickname = null,
			openid = null,
			access_token = null;
		//		alert(oauthtype);
		s.getUserInfo(function(data) {
			userinfo = data.target.userInfo;
			//			console.log(JSON.stringify(data));return;
			switch(oauthtype) {
				case 'weixin':
					//					avatar = userinfo.headimgurl;//头像 
					//					name = userinfo.nickname;  
					openid = data.target.authResult.openid;
					access_token = data.target.authResult.access_token;
					break;
				case 'qq':
					//					avatar = userinfo.figureurl_qq_2;//头像 
					//					name = userinfo.nickname;
					openid = data.target.authResult.openid;
					access_token = data.target.authResult.access_token;
					figureurl_qq_2 = userinfo.figureurl_qq_2;
					nickname = userinfo.nickname;
					gender = userinfo.gender;
					break;
				case 'sinaweibo':
					access_token = data.target.authResult.token; //头像 
					openid = data.target.authResult.uid;
					break;
			}

			if(oauthtype == 'weixin') {
				var login_url = apiRoot + '?act=connect&op=get_wx_info&openid=' + openid + "&access_token=" + access_token + "&client=app";
			} else if(oauthtype == 'sinaweibo') {
				var login_url = apiRoot + '?act=connect&op=get_sina_info&accessToken=' + access_token + "&userID=" + openid + "&client=app";
			} else {
				var login_url = apiRoot + '?act=connect&op=get_qq_info&openid=' + openid + '&access_token=' + access_token + '&figureurl_qq_2=' + figureurl_qq_2 + '&nickname=' + nickname + '&gender=' + gender + '&client=app';
			}
			$.ajax({
				url: login_url,
				type: 'get',
				dataType: 'json',
				success: function(data, status, xhr) {
					console.log(JSON.stringify(data));
					if(data.code == 200) {
						plus.nativeUI.closeWaiting();
						toast('登录成功');
						plus.storage.setItem('user', data.datas.username + '');
						plus.storage.setItem('name', data.datas.truename + '');
						plus.storage.setItem('id', data.datas.userid + '');
						plus.storage.setItem('userpic', data.datas.member_avatar + '');
						plus.webview.close()
						relogin(plus.webview.currentWebview().id);

						//							authLogout();
					} else {
						plus.nativeUI.closeWaiting();
						toast(data.datas.error);
					}
				},
				error: function(e) {
					plus.nativeUI.closeWaiting();
					plus.nativeUI.toast("连接失败，请重试。");
					plus.nativeUI.toast(e);
				}
			})

		}, function() {
			plus.nativeUI.closeWaiting();
			plus.nativeUI.toast('获取用户信息失败');
			return;
		})
	}

	//退出登录的判断
	if(spage) {
		var first = null;
		mui.back = function() {
			//首次按键，提示‘再按一次退出应用’
			if(!first) {
				first = new Date().getTime();
				mui.toast('再按一次退出应用');
				setTimeout(function() {
					first = null;
				}, 2000);
			} else {
				if(new Date().getTime() - first < 2000) {
					plus.runtime.quit();
				}
			}
		};
	}

	//退出登录的判断
	if(ads) {
		var first = null;
		mui.back = function() {
			//首次按键，提示‘再按一次退出应用’
			if(!first) {
				first = new Date().getTime();
				mui.toast('再按一次退出应用');
				setTimeout(function() {
					first = null;
				}, 2000);
			} else {
				if(new Date().getTime() - first < 2000) {
					plus.runtime.quit();
				}
			}
		};
	}

}, false);

// 注销所有授权登录认证服务
function authLogout() {
	console.log("注销授权 " + auths);
	for(var i in auths) {
		var s = auths[i];
		if(s.authResult) {
			s.logout(function(e) {
				console.log("注销登录认证成功！");
			}, function(e) {
				console.log("注销登录认证失败！");
			});
		}
	}
}

function dingwei(){
	var lng = lat = '';
	plus.geolocation.getCurrentPosition(function(p){
		lat = p.coords.latitude;  
		lng = p.coords.longitude; 
//		console.log(lat+'--'+lng);
		if(lat > 0 || lng > 0){
//			console.log(lat+'--'+lng);
			plus.storage.setItem('lat',lat + '');
			plus.storage.setItem('lng',lng + '');
			$.ajax({
				type:"post",
				url:apiRoot + "?act=index&op=map",
				data:{
					lat : lat,
					lng : lng
				},
				dataType:'json',
				success:function(data){ 
//					console.log(JSON.stringify(data));
					if(data.code == 200){
						plus.storage.setItem('store_id', data.datas.store_id); //定位商家id
						plus.storage.setItem('store_name', data.datas.store_name); //定位商家id
					}else{
						nomap();
					}
					
				},
				error:function(e){
					error();
				}
			});
		}else{
			nomap();
		}
	}, function ( e ) {
		console.log( "Geolocation error: " + e.message );
	},{
    	provider:'baidu',
        coordsType:'bd09ll', 
        geocode:true
	}); 
}

function nomap(){
	$.ajax({
		type:"post",
		url:apiRoot + "?act=index&op=nomap",
		dataType:'json',
		success:function(data){
			if(data.code == 200){
				plus.storage.setItem('store_id', data.datas.store_id); //定位商家id
				plus.storage.setItem('store_name', data.datas.store_name); //定位商家id			
			}
		},
		error:function(e){
			error();
		}
	});
}
